const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');
const os = require('os');
const app = express();
const PORT = 8061;

// 目标服务器
const TARGET = 'http://222.134.12.238:8060/auto-api';

// 配置跨域和安全头中间件
app.use((req, res, next) => {
  // 添加安全头
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');
  res.setHeader('Access-Control-Allow-Credentials', 'true');

  // 允许使用worker和内联脚本
  res.setHeader('Content-Security-Policy', "default-src 'self' * blob: data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: data:; worker-src 'self' blob: data:; img-src 'self' * blob: data:; style-src 'self' 'unsafe-inline' *; connect-src 'self' *");

  // 处理OPTIONS请求
  if (req.method === 'OPTIONS') {
    return res.status(200).end();
  }

  next();
});

// 静态文件服务 - 从web目录提供静态文件
app.use(express.static(path.join(__dirname, 'web'), {
  setHeaders: (res) => {
    // 为静态资源添加安全头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Content-Security-Policy', "default-src 'self' * blob: data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: data:; worker-src 'self' blob: data:; img-src 'self' * blob: data:; style-src 'self' 'unsafe-inline' *; connect-src 'self' *");
  }
}));

// 设置代理中间件选项
const proxyOptions = {
  target: TARGET,
  changeOrigin: true,
  secure: false,
  ws: true,
  onProxyReq: (proxyReq, req, res) => {
    // 可以在这里修改请求头
  },
  onProxyRes: (proxyRes, req, res) => {
    // 修改响应头以允许跨域
    proxyRes.headers['Access-Control-Allow-Origin'] = '*';
    proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, PATCH, DELETE';
    proxyRes.headers['Access-Control-Allow-Headers'] = 'X-Requested-With,content-type,Authorization';
    proxyRes.headers['Access-Control-Allow-Credentials'] = 'true';

    // 修改或移除可能引起问题的内容安全策略
    delete proxyRes.headers['content-security-policy'];
    delete proxyRes.headers['content-security-policy-report-only'];

    // 添加允许Web Worker的内容安全策略
    proxyRes.headers['Content-Security-Policy'] = "default-src 'self' * blob: data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: data:; worker-src 'self' blob: data:; img-src 'self' * blob: data:; style-src 'self' 'unsafe-inline' *; connect-src 'self' *";
  },
  // 只有非静态资源才代理
  filter: (pathname) => {
    return !pathname.match(/\.(js|css|html|ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/i);
  }
};

// 所有请求都经过代理中间件处理
app.use('/', createProxyMiddleware(proxyOptions));

// 对于所有其他请求，返回web目录中的index.html，以支持前端路由
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'web', 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
  const networkInterfaces = os.networkInterfaces();
  const localIP = Object.values(networkInterfaces)
    .flat()
    .find(interface => interface.family === 'IPv4' && !interface.internal)?.address || 'localhost';

  console.log(`本地静态文件服务已启动在端口: ${PORT}`);
  console.log(`API请求代理到: ${TARGET}`);
  console.log(`静态资源从目录提供: ${path.join(__dirname, 'web')}`);
  console.log(`请访问: http://localhost:${PORT}/index.html`);
  console.log(`或访问: http://${localIP}:${PORT}/index.html`);
}); 